##################################################################################################################################
#
# Copyright (C) 2008-2013 Mind System Connection. Lda. Part of Daidze Software, created by Siqsuruq. All other rights reserved.
#
# Mind System Connection Webpage: www.msysc.org
# Daidze Software Page: www.daidze.com www.daidze.org
# E-mail: admin@msysc.org, siqsuruq@gmail.com
#
##################################################################################################################################

oo::class create my_print {
	constructor {xml_file data} {
############################################################################################################################
#		Parsing XML model 
############################################################################################################################
		my variable doc
		set doc [dom parse [tDOM::xmlReadFile $xml_file]]
		set root [$doc getElementsByTagName page]
		set nodes [$root childNodes]

############################################################################################################################
#		Processing data dictionary, seting up current variables
############################################################################################################################
		my variable obj_vars
		set obj_vars [list]
		foreach key [dict keys $data] val [dict values $data] {
			my variable $key
			set $key $val
			lappend obj_vars $key
		}

		# puts "Object variables: $obj_vars"
		# puts "Data: $data"
############################################################################################################################
#		Loading fonts files, creating fonts 
############################################################################################################################
		pdf4tcl::new mypdf -paper [$root getAttribute format] -margin "80 80 90 90" -landscape [$root getAttribute layout]
		pdf4tcl::loadBaseTrueTypeFont normal "[file join $::fonts TitilliumWeb-Regular.ttf]"
		pdf4tcl::loadBaseTrueTypeFont bold "[file join $::fonts Comfortaa-Bold.ttf]"
		pdf4tcl::createFont normal normal cp1252
		pdf4tcl::createFont bold bold cp1252

############################################################################################################################
#		Calculate printable width and heigth of the page  
############################################################################################################################
		my variable print_width 
		puts "Print width: [set print_width [lindex [mypdf getDrawableArea] 0]]"
		lappend obj_vars print_width
		my variable print_height
		set print_height [lindex [mypdf getDrawableArea] 1]
		lappend obj_vars print_height

############################################################################################################################
#		Processing Header Body and Footer  
############################################################################################################################
		mypdf startPage
		my Header
		my Body
		my Footer

############################################################################################################################
#		Writing file to export directory, opening it with pdf viewer
############################################################################################################################
		set doc_name [subst [$root getAttribute name]]
		if {[catch {mypdf write -file [file join $::export_dir $doc_name.pdf]} errmsg]} {
			audit::audit pdf_create 1 "Error generating pdf: $errmsg"
			tk_messageBox -icon info -type ok -message "[::msgcat::mc "Document is already open."]"
		} else {
			mypdf write -file [file join $::export_dir $doc_name.pdf]
			exec $::pdf_viewer [file join $::export_dir $doc_name.pdf] &
		}
		mypdf destroy
	}



	method Header {} {
		my variable doc
		mypdf setTextPosition 0 0
		set header [$doc getElementsByTagName header]
		set nodes [$header childNodes]
		my Process_nodes $nodes
	}

	method Body {} {
		my variable doc
		mypdf setTextPosition 0 [my Cur_y]
		set body [$doc getElementsByTagName body]
		set nodes [$body childNodes]
		my Process_nodes $nodes
	}

	method Footer {} {
		my variable doc
		mypdf setTextPosition 0 652
		set footer [$doc getElementsByTagName footer]
		set nodes [$footer childNodes]
		my Process_nodes $nodes
	}

	method Process_nodes {nodes} {
		my variable obj_vars
		foreach var $obj_vars {
			my variable $var
# puts $var
		}

		foreach node $nodes {
			if {[$node nodeName] == "line"} {
				mypdf line 0 [expr [lindex [mypdf getTextPosition] 1]+5] $print_width [expr [lindex [mypdf getTextPosition] 1]+5]
				mypdf newLine 2
			} elseif {[$node nodeName] == "textbox"} {
				my Fonts $node
				set r [$node childNodes]
				set subst_text "[subst [$r nodeValue]]"
				mypdf drawTextBox [my Cur_x] [my Cur_y] $print_width 200 $subst_text
				mypdf newLine 2
			} elseif {[$node nodeName] == "empty"} {
				mypdf newLine 1
			} elseif {[$node nodeName] == "table"} {
				my Fonts $node


				set col_width [$node getAttribute col_width]
				set col_align [$node getAttribute col_align]
				if {[$node hasAttribute sep_num] != 0} {
					set sep_num [$node getAttribute sep_num]
				} else {
					set sep_num [list]
					foreach dummy $col_align {
						lappend sep_num n
					}
				}
				set font_height [expr [mypdf getFontMetric height] + 2]
				set y_start [my Cur_y]
				set x_start 0

				if {[set headers [$node getAttribute headers]] != "no"} {
					foreach head $headers w $col_width align $col_align {
						mypdf setFont 8 bold

						if {$align == "m"} {
							set end_x [expr $x_start + ($print_width / 100 * $w)]
							set str_width [mypdf getStringWidth \"$head\"]
							set half [expr $str_width / 2]
							set b_width [expr $end_x - $x_start]
							set align_x [expr $b_width / 2 - $half]
							mypdf setTextPosition $align_x $y_start
						} elseif {$align == "r"} {
							set end_x [expr $x_start + ($print_width / 100 * $w)]
							set str_width [mypdf getStringWidth "$head"]
							set align_x [expr $end_x - $str_width]
							mypdf setTextPosition $align_x $y_start
						} else {
							mypdf setTextPosition $x_start $y_start
						}

						mypdf text $head
						set x_start [expr $x_start + ($print_width / 100 * $w)]
					}
				}
				mypdf newLine 1

				set r [subst $[$node getAttribute var]]
				mypdf setFont 7 normal
				foreach row [dict keys $r] rdata [dict values $r] {
					set line_data [dict values $rdata]

					puts "y inicial: [set y_start [my Cur_y]]"
					set x_start 0
					foreach head $line_data w $col_width align $col_align sep $sep_num {
					if {$y_start == 600} {
					mypdf startPage
					set y_start 0}
						if {$align == "m"} {
							set end_x [expr $x_start + ($print_width / 100 * $w)]
							if {$sep == "y"} {
								set str_width [mypdf getStringWidth \"[commify $head]\"] 
							} else {
								set str_width [mypdf getStringWidth \"$head\"]
							}
							set half [expr $str_width / 2]
							set b_width [expr $end_x - $x_start]
							set align_x [expr $b_width / 2 - $half]
							mypdf setTextPosition $align_x $y_start
						} elseif {$align == "r"} {
							set end_x [expr $x_start + ($print_width / 100 * $w)]
							if {$sep == "y"} {
								set str_width [mypdf getStringWidth \"[commify $head]\"] 
							} else {
								set str_width [mypdf getStringWidth \"$head\"]
							}
# 							set str_width [mypdf getStringWidth "$head"]
							set align_x [expr $end_x - $str_width]
							mypdf setTextPosition $align_x $y_start
						} else {
							mypdf setTextPosition $x_start $y_start
						}
						if {$sep == "y"} {
							mypdf text [commify $head]
						} else {
							mypdf text $head
						}

						set x_start [expr $x_start + ($print_width / 100 * $w)]
					}
					mypdf newLine 1
				}

			} elseif {[$node nodeName] == "vartext"} {
				my Fonts $node
				mypdf setFont 8 normal
				set r [$node childNodes]
				set subst_label "[subst [$r nodeValue]]"
				set subst_value "[commify [subst [$node getAttribute var]]]"
				mypdf drawTextBox 0 [my Cur_y] $print_width 20 $subst_label
				mypdf setFont 8 bold
				set str_width [mypdf getStringWidth $subst_value]
				mypdf setTextPosition [expr $print_width  - $str_width] [my Cur_y]
				mypdf text $subst_value
				mypdf newLine 1

			} elseif {[$node nodeName] == "fixtext"} {

				mypdf setTextPosition [$node getAttribute x] [$node getAttribute y]
				my Fonts $node
# 				mypdf setFont 8 normal
				set r [$node childNodes]

				set subst_value "[subst [$r nodeValue]]"
				mypdf text $subst_value
				mypdf newLine 1
				
			} elseif {[$node nodeName] == "image"} {
				set r [$node childNodes]
				set subst_value "[subst [$r nodeValue]]"
				if {$subst_value ne ""} {
					set tmp_doc [::fileutil::tempfile]
					set tmp_file [open $tmp_doc w+]
					fconfigure $tmp_file -translation binary
					puts $tmp_file [pg_unescape_bytea $subst_value]
					close $tmp_file

					image create photo img1 -file $tmp_doc
					set imgdata [img1 data]

					set imgid [mypdf addRawImage $imgdata]
					set imgsize [mypdf getImageSize $imgid]
					if {[$node hasAttribute width] != 0} {
						set imgwidth [$node getAttribute width]
					} else {
						set imgwidth [lindex $imgsize 0]
					}
					if {[$node hasAttribute height] != 0} {
						set imgheight [$node getAttribute height]
					} else {
						set imgheight [lindex $imgsize 1]
					}
					mypdf putImage $imgid [$node getAttribute x] [$node getAttribute y] -width $imgwidth -height $imgheight
				}
				mypdf newLine 1

			} else {
				my Fonts $node
				set r [$node childNodes]
				my Align $node
				set subst_text "[subst [$r nodeValue]]"
				mypdf text $subst_text
				mypdf setTextPosition 0 [my Cur_y]
				mypdf newLine 1
			}
		}

	}

	method Fonts {node} {
		if {[$node hasAttribute weight] != 0 && [$node getAttribute weight] == "bold"} {
			set weight bold
		} else {
			set weight normal
		}
		if {[$node hasAttribute size] != 0} {
			set size [$node getAttribute size]
		} else {
			set size 10
		}
		mypdf setFont $size $weight
	}

	method Align {node} {
		my variable print_width
		set r [$node childNodes]
		if {[$node hasAttribute align] != 0 && [$node getAttribute align] == "center"} {
			set str_width [mypdf getStringWidth "[$r nodeValue]"]
			mypdf setTextPosition [expr $print_width / 2 - ($str_width / 2)] [my Cur_y]
		} elseif {[$node hasAttribute align] != 0 && [$node getAttribute align] == "left"} {
			set str_width [mypdf getStringWidth "[$r nodeValue]"]
			mypdf setTextPosition [expr $print_width  - $str_width] [my Cur_y]
		} else {
			mypdf setTextPosition 0 [my Cur_y]
		}

	}

	method Cur_x {} {
		set cur_x [lindex [mypdf getTextPosition] 0]
		return $cur_x
	}

	method Cur_y {} {
		set cur_y [lindex [mypdf getTextPosition] 1]
		return $cur_y
	}
	
	destructor {
		
	}
}